#include "image_area.h"

bool ImageArea::isEmpty() const
{
    return _image.isNull();
}

void ImageArea::resizeEvent(QResizeEvent *)
{
    _image = _defaultImage.scaled(this->width()-18, this->height()-6);
}

ImageArea::ImageArea(QWidget* parent, int x, int y, int width, int height, int id, int serial) :
        Area(parent, x, y, width, height, id, serial)
{
    _isResizable = true;
}

void ImageArea::setData(const QByteArray &data, bool default_size)
{
    _data = data;
    _defaultImage.loadFromData(data);

    if (default_size)
    {
        _image = _defaultImage;
        if(_image.width()>640 || _image.height()>480)
        {
            float scale = 0;
            if (_image.width() > _image.height())
            {
                scale = _image.width() / 640;
                _image = _defaultImage.scaled(int(_image.width()/scale), int(_image.height()/scale));
            }
            else
            {
                scale = _image.height() / 480;
                _image = _defaultImage.scaled(int(_image.width()/scale), int(_image.height()/scale));
            }
        }
        this->setGeometry(x(), y(), _image.width()+18, _image.height()+6 );
    }
}

void ImageArea::paintEvent(QPaintEvent *)
{
    QPainter painter;
    painter.begin(this);
        painter.drawImage(QPoint(15,3), _image);
    painter.end();
}

QByteArray ImageArea::contains() const
{
    return ("<object type=image x="+
            QByteArray::number(this->x())+" y="+
            QByteArray::number(this->y())+" w="+
            QByteArray::number(this->width())+" h="+
            QByteArray::number(this->height())+" r="+
            QByteArray::number(_color.red())+" g="+
            QByteArray::number(_color.green())+" b="+
            QByteArray::number(_color.blue())+" serial="+
            QByteArray::number(_serial)+">"+_data+"</object>\n");
}
